package com.gec.common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.sql.SQLIntegrityConstraintViolationException;

/**全局异常处理器
 * 拦截带有RestController和Controller注解的类 @ControllerAdvice(annotations = {RestController.class, Controller.class})
 * @author : [chenxys]
 * @version : [v1.0]
 */
@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    /**
     * 处理SQLIntegrityConstraintViolationException异常
     * @author chenxys
     * @return com.gec.common.R<java.lang.String>
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        // 判断异常信息里是否存在 Duplicate entry
        if (ex.getMessage().contains("Duplicate entry")){
            // 违反唯一约束
            String[] split = ex.getMessage().split(" ");
            // 0          1     2
            // Duplicate entry 'hehe' for key 'idx_username'
            String message = split[2] + "已存在";
            return R.error(message);
        }
        return R.error("未知错误");
    }


    /**
     * 处理自定义异常
     * @author chenxys
     * @return com.gec.common.R<java.lang.String>
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        // 返回异常信息
        return R.error(ex.getMessage());
    }

}
